<template>
  <div class="map-application">
    <!-- 地图容器组件 -->
    <MapContainer @map-ready="onMapReady" ref="mapContainerRef">
      <!-- 绘图工具组件 - 改进条件渲染和属性传递 -->
      <DrawTools v-if="appStore.isMapReady" 
                :map="appStore.mapInstance" 
                :sourceFeatures="appStore.sourceFeaturesInstance"
                :is2D="appStore.is2DMode" />
      
      <!-- 测量工具组件 - 使用完整参数传递 -->
      <MeasureTools v-if="appStore.isMapReady" :map="appStore.mapInstance" :measureTools="appStore.measureToolsInstance" />
      
      <!-- 轨迹回放组件 -->
      <TrajectoryPlayer v-if="appStore.isMapReady" />
    </MapContainer>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, provide, reactive, watch } from 'vue';
import MapContainer from '@/components/MapContainer.vue';
import DrawTools from './DrawTools.vue';
import MeasureTools from '@/components/MeasureTools.vue';
import TrajectoryPlayer from './TrajectoryPlayer.vue';
import { getMeasureTools } from '@/hooks';
import { useAppStore } from '@/stores/modules/app';

// 使用应用级store
const appStore = useAppStore();

// 地图容器组件引用
const mapContainerRef = ref(null);

// 测量工具单例，仅在需要时初始化
const initMeasureToolsInstance = () => {
  if (!appStore.measureToolsInstance) {
    console.log('初始化测量工具单例');
    const measureTools = getMeasureTools();
    appStore.setMeasureToolsInstance(measureTools);
  }
  return appStore.measureToolsInstance;
};

// 初始化测量工具
function initMeasureTools() {
  console.log('初始化测量工具');
  const measureTools = initMeasureToolsInstance();

  if (appStore.mapInstance && measureTools) {
    try {
      const initialized = measureTools.initMap(appStore.mapInstance);
      console.log('测量工具初始化结果:', initialized ? '成功' : '失败');
    } catch (error) {
      console.error('初始化测量工具时出错:', error);
    }
  } else {
    console.warn('地图或测量工具不可用，无法初始化测量工具');
  }
}

/**
 * 处理地图准备就绪事件
 */
function onMapReady(data) {
  console.log('地图准备就绪事件触发:', data);
  
  // 使用store初始化地图应用
  const success = appStore.initMapApp(data);
  
  if (success) {
    // 初始化测量工具
    initMeasureTools();
  } else {
    // 尝试再次获取
    setTimeout(() => {
      if (mapContainerRef.value) {
        tryGetMapFromRef();
      }
    }, 500);
  }
}

// 从ref中获取地图实例的函数
function tryGetMapFromRef() {
  if (!mapContainerRef.value) return false;
  
  try {
    // 尝试获取地图实例和要素源
    const map = mapContainerRef.value.getMap();
    const sourceFeatures = mapContainerRef.value.getSourceFeatures();
    const is2D = mapContainerRef.value.getIs2D();
    
    console.log('从ref获取地图信息:', map, sourceFeatures, is2D);
    
    // 仅当都获取到时才更新
    if (map && sourceFeatures) {
      // 使用store更新状态
      appStore.setMapInstance(map);
      appStore.setSourceFeaturesInstance(sourceFeatures);
      appStore.setIs2DMode(is2D !== undefined ? is2D : true);
      appStore.setMapReady(true);
      
      // 将地图实例添加到window上，以便测量组件可以查找
      window.mapInstance = map;
      
      // 将地图实例存储到map元素上
      try {
        const mapElement = document.getElementById('map');
        if (mapElement) {
          mapElement.__map = map;
        }
      } catch (e) {
        console.error('保存地图实例到DOM元素失败:', e);
      }
      
      // 如果是3D模式，初始化环绕功能
      if (!is2D) {
        init3DOrbit(map);
      }
      
      return true;
    }
  } catch (error) {
    console.error('获取地图实例失败:', error);
  }
  
  return false;
}

// 初始化3D环绕功能
function init3DOrbit(map) {
  if (!map) return;
  
  try {
    // 获取地图视图
    const view = map.getView();
    if (!view) return;
    
    // 设置初始视角
    view.setCenter([0, 0]);
    view.setZoom(2);
    
    // 添加环绕动画
    let angle = 0;
    const radius = 10000000; // 环绕半径
    const center = [0, 0]; // 环绕中心点
    
    function animate() {
      angle += 0.001; // 旋转速度
      
      // 计算新位置
      const x = center[0] + radius * Math.cos(angle);
      const y = center[1] + radius * Math.sin(angle);
      
      // 更新视角
      view.animate({
        center: [x, y],
        duration: 100,
        easing: ol.easing.linear
      });
      
      // 继续动画
      requestAnimationFrame(animate);
    }
    
    // 开始动画
    animate();
    
    console.log('3D环绕功能已初始化');
  } catch (error) {
    console.error('初始化3D环绕功能失败:', error);
  }
}

// 监听地图模式变化
watch(() => appStore.is2DMode, (is2D) => {
  console.log('地图模式已切换:', is2D ? '2D' : '3D');
  
  if (!is2D && appStore.mapInstance) {
    // 切换到3D模式时初始化环绕功能
    init3DOrbit(appStore.mapInstance);
  }
});

// 为子组件提供地图实例和源
provide('mapApp', reactive({
  ready: computed(() => appStore.isMapReady),
  map: computed(() => appStore.mapInstance),
  sourceFeatures: computed(() => appStore.sourceFeaturesInstance),
  is2D: computed(() => appStore.is2DMode),
  map3d: computed(() => appStore.map3dInstance)
}));

// 提供单独的引用给子组件 - 直接提供实例而不是ref
watch(() => appStore.mapInstance, (newMap) => {
  if (newMap) {
    console.log('直接提供地图实例给子组件');
    provide('map', newMap);
  }
}, { immediate: true });

watch(() => appStore.map3dInstance, (newMap3d) => {
  provide('map3d', newMap3d);
}, { immediate: true });

// 对于is2D，提供引用而不是值，避免"Cannot create property value on boolean true"错误
provide('is2D', computed(() => appStore.is2DMode));

provide('mapContainerRef', mapContainerRef);

// 检查组件挂载后初始化状态
onMounted(() => {
  console.log('MapApplication组件已挂载');
  
  const checkInit = () => {
    console.log('检查地图初始化状态:', {
      'mapReady': appStore.isMapReady,
      'mapInstance': !!appStore.mapInstance,
      'sourceFeatures': !!appStore.sourceFeaturesInstance
    });
    
    if (!appStore.isMapReady && mapContainerRef.value) {
      console.log('地图尚未就绪，尝试从ref获取');
      tryGetMapFromRef();
    }
  };
  
  // 延迟检查初始化状态
  setTimeout(checkInit, 1500);
});
</script>

<style scoped>
.map-application {
  width: 100%;
  height: 100vh;
  position: relative;
}
</style> 